﻿

function ProfileController() {

    var schedulerController = new SchedulerController(new SchedulerView(), new Scheduler());
    var view = new ProfileView(this);
    var model = new ProfileModel();



    function Wrap(schedule) 
    {
        var wrappedSchedule = [];

        for (var i = 0; i < schedule.length; ++i) {
            var intervals = schedule[i].GetIntervals();
            for (var j = 0; j < intervals.length; ++j) 
            {
                wrappedSchedule.push
                (
                    {
                        DayOfWeek: schedule[i].GetWeekDayName(),
                        StartTime: intervals[j].GetStartTime(),
                        EndTime: intervals[j].GetEndTime()
                    }
                )
            }
            }
            return wrappedSchedule;
           
    }
    
    this.UpdateCallback = function (typesOfVolunteering, destinataries, areasOfVolunteering) {


        model.SendToServer
        (
            function(result)
            {
                view.SetResultMessage(result);
            },
            Wrap(schedulerController.GetSchedule()),
            typesOfVolunteering,
            destinataries,
            areasOfVolunteering
        );
    }

    $(view.init);
    


    
};

function ProfileModel() {
    this.SendToServer = function(callback, schedule,typesOfVolunteering,destinataries,areasOfVolunteering )
    {
        var postData = makeArrayParams(schedule,ProfileModel.SCHEDULE);
        makeArrayParams(typesOfVolunteering,ProfileModel.TYPEOFVOLUNTEERING,postData);
        makeArrayParams(destinataries,ProfileModel.DESTINATARIES,postData);
        makeArrayParams(areasOfVolunteering,ProfileModel.AREASOFVOLUNTEERING,postData);
        $.ajax(
           {
            type: "POST",
            url: ProfileModel.SEVERACTIONMETHOD,
            dataType:"json",
            data: postData,
            success: function (val) {
                callback(val); 
            }
            });


    }
}

function ProfileView(controller) {
    var container;

    var getValuesFromCheckBoxList = function(id)
    {
        var arr = [];
        $("#" + id + " input[type=checkbox]:checked")
                .each(function()
                {
                    arr.push($(this).attr('name'));
                });
        return arr;
    };

    var getTypesOfVolunteering = function () { return getValuesFromCheckBoxList('TypeofVolunteering'); }
    var getDestinataries = function () { return getValuesFromCheckBoxList('Destinataries');}
    var getAreasOfVolunteering = function () { return getValuesFromCheckBoxList('AreaofVolunteering');}
    var message =   $('<h3></<h3>');
                        
    this.init = function () {
        container = $('#voluteering-content');
        var button = $('<a></a>').appendTo(container)
                                 .text('Update')
                                 .button()
                                 .click(function (evt, m) {
                                     message.remove();
                                     controller.UpdateCallback
                                        (
                                            
                                            getTypesOfVolunteering(),
                                            getDestinataries(),
                                            getAreasOfVolunteering()
                                        );
                                 });


    };

    this.SetResultMessage = function(msg){
        message.text(msg).appendTo(container);
    }


};
var _ = new ProfileController();


function CallServerAsync (parameters, method, serverHandler, callback)
{
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4 && xhr.status >= 400) {
		    ;
		}
		if (xhr.readyState == 4 && xhr.status == 200) {
		    var response = jQuery.parseJSON(xhr.responseText, true);

		    callback(response);
		}
	}


	if (method == 'POST') {
		xhr.open(method, serverHandler, true);
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xhr.setRequestHeader("Content-length", parameters.length);
		xhr.setRequestHeader("Connection", "close");
		xhr.send(parameters);
	}
	else {
		xhr.open(method, serverHandler + parameters, true);
		xhr.send(null);
	}
}

function makeArrayParams(arr, namespace, tempObj) {
    if(tempObj == undefined)
        tempObj = {};
    for (var i = 0; i < arr.length; i++) {
        var o = arr[i];

        if(typeof(o) == "string")
        {
            tempObj[namespace + "[" + i + "]"] = o;
            continue;
        }
        for (var k in o) {
                tempObj[namespace + "[" + i + "]." + k] = o[k] instanceof Date? o[k].toGMTString() : o[k];
        }
    }
    return tempObj;
    };